#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/22  18:40
# @Author: 余浪人
# @email: yulangren520@gmail.com

import js2py
from urllib import parse
from flask_login import LoginManager
from apps.models.member_model import TL_Member_Model

login_manager = LoginManager()


@login_manager.user_loader
def load_user(user_id):
    try:
        return TL_Member_Model.query.filter_by(id=int(user_id)).first()
    except:
        return None

def parse_quote(string: str):
    '''
    对字符串进行url编码
    :param string: 待编码字符串
    :return: 编码结果
    '''
    return parse.quote(string)


def get_token(qrsig):
    js = '''
    function param(t) {
    for (var e = 0, i = 0, n = t.length; i < n; ++i)
    e += (e << 5) + t.charCodeAt(i);
    return  2147483647 & e
    }
    '''
    param = js2py.eval_js(js)  # 加载JS文件
    return param(qrsig)  # 调用js方法  第一个参数是JS的方法名，后面的data和key是js方法的参数


def createCookie(cookie: dict):
    '''
    将字典转化cookie字符串
    :param cookie: 字典
    :return: cookie字符串
    '''
    cookieVal = ';'.join(
        [f'{k}={v}' for k, v in cookie.items()])
    return cookieVal
